package com.easyselection.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easyselection.dto.Result;
import com.easyselection.dto.ScrollResult;
import com.easyselection.dto.UserDTO;
import com.easyselection.entity.Blog;
import com.easyselection.entity.Follow;
import com.easyselection.entity.User;
import com.easyselection.mapper.BlogMapper;
import com.easyselection.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easyselection.service.IFollowService;
import com.easyselection.service.IUserService;
import com.easyselection.utils.RedisConstants;
import com.easyselection.utils.SystemConstants;
import com.easyselection.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    /**
     * 设置点赞功能
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //2.判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet()
                .score(key, userId.toString());
        if(score == null) {
            //3.如果未点赞, 可以点赞
            //3.1数据库字段liked + 1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            //3.2将当前用户保存到zset集合当中 zadd key score member
            if(isSuccess)
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
        }else {
            //4.如果已点赞, 则取消点赞
            //4.1数据库字段liked - 1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            //4.2将当前用户从zset集合当中移除
            if(isSuccess)
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
        }
        return Result.ok();
    }

    /**
     * 点赞排行榜
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        //1.查询top5的点赞用户 zrange key min max
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()) return Result.ok(Collections.emptyList());
        //2.解析出用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.根据用户id查询用户 where id in(5, 4) order by field(id, 5, 4)
        String idStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService
                .query().in("id", ids).last("order by field(id," + idStr + ")").list()
                //.listByIds(ids)
                .stream()
                .map(user -> {
                    return BeanUtil.copyProperties(user, UserDTO.class);
                }).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    /**
     * 保存当前用户的探店博文
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店博文
        //shop_id是否为空,
        if(blog.getShopId() == null) return Result.fail("您还未关联商户哦~");
        boolean isSuccess = save(blog);
        if(!isSuccess){
           return Result.fail("blog笔记不存在!");
        }
        // 3.查询笔记作者的所有粉丝 select * from tb_follow where follow_user_id = ?
        List<Follow> fansUsers = followService.query().eq("follow_user_id", user.getId()).list();
        // 4. 推送笔记id给所有粉丝
        for (Follow fans : fansUsers) {
            //4.1获取粉丝id
            Long userId = fans.getUserId();
            //4.2 推送
            String key = RedisConstants.FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }

        // 5.返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;
        //2.查询收件箱 ZREVRANGEBYSCORE KEY max min LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.非空判断
        if(typedTuples == null || typedTuples.isEmpty()) return Result.ok();

        //4.解析数据 blogId、minTime(时间戳)、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int count = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //4.1 获取blogId
            String idStr = typedTuple.getValue();
            ids.add(Long.valueOf(idStr));
            //4.2 获取分数时间戳
            long time = typedTuple.getScore().longValue();
            if(time == minTime) count++;
            else{
                minTime = time;
                count = 1;
            }
        }
        //4.根据blogId查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            //根据blog查询相关用户
            queryBlogUser(blog);
            //查询blog是否已被点赞
            isBlogLiked(blog);
        }

        //5.封装结果返回
        ScrollResult sr = new ScrollResult();
        sr.setList(blogs);
        sr.setMinTime(minTime);
        sr.setOffset(count);
        return Result.ok(sr);
    }

    /**
     * 博客分页数据
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 根据博客id查询博客
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        //1.查询blog
        Blog blog = getById(id);
        if(blog == null) return Result.fail("blog不存在!");
        //2.根据blog查询相关用户
        queryBlogUser(blog);
        //3.查询blog是否已被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 设置博客是否被点赞(blog的IsLike属性)
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        //1.获取当前登录用户
        UserDTO user = UserHolder.getUser();
        //如果不判空, 对于未登录用户,再去走user.getId()会报空指针异常
        if(user == null) return;//如果用户没有登录, 则不用走该博客是否被点赞的逻辑
        Long userId = user.getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        //2.判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet()
                .score(key, userId.toString());
        blog.setIsLike(score != null);
    }


    /**
     * 增加博客关联的用户名及用户头像信息
     * @param blog
     */
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


}
